<template>
  <Dialog
    class="edit-dialog"
    title="添加角色权限"
    :visible.sync="dialogVisible"
    @submit="submit"
  >
    <vue-scroll>
      <el-tree
        ref="menuTree"
        :data="menuList"
        show-checkbox
        node-key="id"
        :props="defaultProps"
        :default-expanded-keys="defaultKeys"
        :default-checked-keys="defaultKeys"
      />
    </vue-scroll>
  </Dialog>
</template>

<script>
import { getMenuListAll, inPowerMenu, getPowerMenuList } from "@/api/role";

export default {
  name: "EditRole",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    roleInfo: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      //对话框状态--------------------------------------------
      dialogVisible: this.visible,
      //权限列表--------------------------------------------
      menuList: [],
      //默认选中的列表--------------------------------------------
      defaultKeys: [],
      //树形控件配置--------------------------------------------
      defaultProps: {
        children: "child",
        label: "menuName"
      }
    };
  },

  watch: {
    //监听对话框状态--------------------------------------------
    dialogVisible(newVal) {
      this.$emit("update:visible", newVal);
    }
  },

  created() {
    this.getPowerMenuList();
  },

  methods: {
    //获取该角色的权限列表--------------------------------------------
    async getPowerMenuList() {
      this.defaultKeys = [];
      const params = {
        uuid: this.roleInfo.uuid
      };
      const res = await getPowerMenuList(params).catch(res => console.log(res));
      res.items.forEach(item => {
        this.defaultKeys.push(item.menuId);
      });
      this.getMenuListAll();
    },

    //获取全部权限列表--------------------------------------------
    async getMenuListAll() {
      const res = await getMenuListAll().catch(res => console.log(res));
      this.menuList = res.items;
    },

    //确定提交--------------------------------------------
    submit() {
      const menuTree = this.$refs.menuTree;
      const data = {
        list: menuTree.getCheckedKeys().concat(menuTree.getHalfCheckedKeys()),
        uuid: this.roleInfo.uuid
      };

      inPowerMenu(data).then(res => {
        if (res.state == 100) {
          this.$message({ message: res.msg, type: "success" });
          this.dialogVisible = false;
          this.$emit("getPowerList");
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.el-tree {
  min-height: 300px;
  max-height: 500px;
}
</style>
